//WebSocket
let isopen = false;
let lastrequestDevicetime = Date.now();
let timeoutVal: any = null;
const hostname = window.location.hostname; // 返回主机名部分
const port = window.location.port; // 返回端口号
let ws = new WebSocket(`ws://${hostname}/statelistening`);
console.log("hostname", hostname);
console.log("port", port);

export const WebSocketInit = () => {
  try {
    ws.onopen = () => {
      ws.send("login");
      isopen = true;
      console.log("ws.readyState", ws.readyState);
      if (ws.readyState == 1) {
        console.log("WebSocket连接成功...");
        setInterval(function ping() {
          if (isopen) {
            console.log('44',ws.readyState);
            if (ws.readyState === 3) {
              console.log('离线离线');
              WebSocketInit();
            }
            ws.send("heartbeat");
          }
        }, 3000);
      } 
    };
  } catch (error) {
    console.log("err", error);
  }
};
export const WebSocketOnmessage = (cb: Function) => {
  ws.onmessage = async (e) => {
    if (ws.readyState == 3) {
      console.log('333le');
      WebSocketInit();
    }
    if (e.data !== "HeartBeat") {
      FucServerDeviceInfoChanged();
      cb();
    }
  };
};
export const onclose = () => {
  console.log("关闭");
  ws.onclose = async () => {
    console.log("ws close");
    isopen = false;
    setTimeout(function () {
      WebSocketInit();
    }, 3000);
  };
};

export const FucServerDeviceInfoChanged = () => {
  let now = Date.now();
  if (now - lastrequestDevicetime > 500) {
    lastrequestDevicetime = now;
  } else {
    clearTimeout(timeoutVal);
    timeoutVal = setTimeout(function () {
      FucServerDeviceInfoChanged();
    }, 200);
  }
};
